'use strict';
var lmfConfig = require('../config.js');
const systemInfo = wx.getSystemInfoSync();
function AliLogTracker() {
  this.uri_ = lmfConfig.AliLogHost;
  this.params_ = new Array();
}
AliLogTracker.prototype = {
  push: function (key, value) {
    if (!key || !value) {
      return;
    }
    this.params_.push([key, encodeURIComponent(value)].join('='));
  },
  clear: function () {
    this.params_ = [];
  },
  __insterSysInfo: function () {
    var _this = this;

    //插入页面信息
    try {
      var pages = getCurrentPages() || [];

      if (pages.length > 0) {
        var lastPages = pages[pages.length - 1]
        if (lastPages.route) {
          _this.push('pageUrl', lastPages.route);
        }
      }
    } catch (e) {

    }


    //插入用户数据
    try {
      ['openid'].forEach(function (key) {
        var data = wx.getStorageSync(key);
        if (data) {
          _this.push(key, JSON.stringify(data));
        }
      })
    } catch (e) {
    }


    //插入系统信息
    try {
      for (var key in systemInfo) {
        _this.push(key, systemInfo[key]);
      }
      _this.push('alias', lmfConfig.alias)
    } catch (e) {
    }

  },
  logger: function () {
    var _this = this;
    if (systemInfo.platform == 'devtools') return _this.clear();
    var url = this.uri_;
    this.__insterSysInfo();
    url += '&' + _this.params_.join('&');
    _this.clear();
    wx.request({ url: url })
  },

};

module.exports = function (launchOptions) {
  //排除开发平台
  if (systemInfo.platform == 'devtools') {
    return;
  }
   //日志输出
  console['debug'] = function () { };
  let reWriteTypes = ['log', 'warn', 'error'];
  if (systemInfo.system.indexOf('ios') != -1) {
    let version = systemInfo.system.match(/\d+/);
    if (version && (version[0] < 10)) {
      reWriteTypes = ['error']
    }
  }
 
  let _log = new AliLogTracker();
  reWriteTypes.forEach(function (log_type) {
    let _oldFN = console[log_type];
    console[log_type] = function () {
      _oldFN.apply(console, arguments);

      if (typeof arguments[0] == 'string' && arguments[0].indexOf('request begin') == -1 && arguments[0].indexOf('request success') == -1) {
        _log.push('log_type', log_type);
        _log.push('mina_version', lmfConfig.version);

        _log.push('log', JSON.stringify(arguments));
        _log.logger();
      };

    };
  });
};